package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.controller.admin.DishController;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private DishController dishController;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Transactional  //涉及两张表的操作，加入事务
    @Override
    public void save(DishDTO dishDTO) {
        //保存菜品基本信息到dish表
        //DTO转实体
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);


        //调用dishMapper保存菜品信息
        dishMapper.insert(dish);

        //获取dish_id,需要菜品保存成功后才会返回，且要手动开启
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(!flavors.isEmpty()){
            //遍历设置dish_id
            flavors.forEach( flavor->{
                flavor.setDishId(dishId);
            });

            //保存菜品口味信息到dish_flavor表
            //注意一个菜品，可能有多条口味数据，批量插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //开启分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        //调用mapper分页查询菜品
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);

        //获取total和result，封装PageResult
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据id批量删除菜品
     * @param ids
     */
    @Transactional  //涉及两张表的操作，加入事务
    @Override
    public void delete(List<Long> ids) {
        //检查菜品状态 --- 是否存在菜品关联套餐
        List<Long> setmealDishIds = setmealDishMapper.getSetmealDishIdsByDishId(ids);
        if(setmealDishIds != null && !setmealDishIds.isEmpty() ){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //检查菜品状态 --- 是否在售卖中
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //删除菜品在dish表中的数据
        dishMapper.deleteByIdBatch(ids);

        //删除菜品在dish_flavor表中的数据
        dishFlavorMapper.deleteByIdBatch(ids);

    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //查询dish表，获取菜品基础数据
        Dish dish = dishMapper.getById(id);

        //查询dish_flavor表，获取菜品口味数据
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);

        //封装VO对象
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);

        //返回结果
        return dishVO;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        //调用mapper进行查询
        List<Dish> list = dishMapper.list(dish);

        //返回结果
        return list;
    }

    /**
     * 菜品起售或停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //若是停售，与该菜品关联的套餐也要停售
        if(status == StatusConstant.DISABLE){
            //根据菜品id查询setmeal_dish表，得到套餐id
            List<SetmealDish> setmealDishes = setmealDishMapper.getByDishId(id);
            //遍历集合，根据套餐id更改套餐状态
            setmealDishes.forEach(setmealDish -> {
                Setmeal setmeal = Setmeal.builder().id(setmealDish.getSetmealId()).status(status).build();
                setmealMapper.update(setmeal);
            });
        }

        //更新dish表中的菜品状态
        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.update(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
